#!/bin/bash
# 可自定义
MYSQL_USER="remoteuser"
MYSQL_PASSWORD="remotepassword"
MYSQL_PORT=3306
echo "🛠️ 开始安装和配置 MySQL..."
# 安装 MySQL
sudo apt update
sudo apt install -y mysql-server
# 修改配置文件，允许远程连接
sudo sed -i "s/^bind-address.*/bind-address = 0.0.0.0/" /etc/mysql/mysql.conf.d/mysqld.cnf
# 重启 MySQL 服务
sudo systemctl restart mysql
# 设置 root 免密访问（如未设置）
sudo mysql -e "ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY ''; FLUSH PRIVILEGES;"
# 创建远程用户并授权
sudo mysql -e "CREATE USER IF NOT EXISTS '${MYSQL_USER}'@'%' IDENTIFIED BY '${MYSQL_PASSWORD}';"
sudo mysql -e "GRANT ALL PRIVILEGES ON *.* TO '${MYSQL_USER}'@'%' WITH GRANT OPTION;"
sudo mysql -e "FLUSH PRIVILEGES;"
# 开放防火墙端口
if command -v ufw >/dev/null; then
  sudo ufw allow ${MYSQL_PORT}/tcp
fi
# 显示连接信息
MY_IP=$(hostname -I | awk '{print $1}')
echo "✅ MySQL 配置完成！你可以使用以下信息连接："
echo "--------------------------------------------"
echo "🌐 服务器 IP   : ${MY_IP}"
echo "🔌 端口        : ${MYSQL_PORT}"
echo "👤 用户名      : ${MYSQL_USER}"
echo "🔑 密码        : ${MYSQL_PASSWORD}"
echo "🗃️ 默认数据库 : mysql（或自行创建）"
echo "📎 DBeaver 类型: MySQL"
echo "--------------------------------------------"



